package com.jie.component.validation.factory;

import com.jie.common.util.LogUtil;
import com.jie.component.init.base.AbstractApplicationPostConstructHandler;
import com.jie.component.validation.validator.ConstraintValidator;
import org.springframework.context.ConfigurableApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jie
 * @version 1.0 2025-02-11
 */
public class ValidatorFactory extends AbstractApplicationPostConstructHandler {

    private Map<Class<? extends Annotation>, ConstraintValidator> validators;

    @SuppressWarnings("unchecked")
    private Class<? extends Annotation> getAnnotationType(ConstraintValidator validator) {
        return (Class<? extends Annotation>) ((ParameterizedType) validator.getClass()
                .getGenericInterfaces()[0]).getActualTypeArguments()[0];
    }

    public ConstraintValidator getValidator(Class<? extends Annotation> annotationType) {
        return validators.get(annotationType);
    }

    @Override
    public void executeInit(ConfigurableApplicationContext context) {
        LogUtil.initLog("ValidatorFactory 注册校验器");
        validators = new HashMap<>();
        // 注册所有校验器
        context.getBeansOfType(ConstraintValidator.class)
                .values()
                .forEach(validator -> {
                    Class<? extends Annotation> annotationType = getAnnotationType(validator);
                    validators.put(annotationType, validator);
                });
    }

    @Override
    public Integer executeOrder() {
        return 0;
    }
}
